package cn.lefull.jpa.codegenerate;

import cn.lefull.jpa.utils.DateTimeUtil;
import cn.lefull.jpa.utils.StringTool;
import cn.lefull.jpa.utils.Tool;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;


/**
 *
 * @author qijiang
 * @date 2018/10/15 上午11:41
 * @Param
 * @return
 * @Description 自动生成实体，DAO等文件
 */
public class CreatCode {

    //删除标志字段
    private final static String is_delete = "is_delete";
    private final static String create_time = "create_time";
    private final static String delete_time = "delete_time";
    private final static String update_time = "update_time";

    //数据库配置
    private final static String diver = "com.mysql.jdbc.Driver";
    public final static String url = "jdbc:mysql://123.56.216.225:3306/pms?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false";

    public final static String db_user = "root";
    public final static String db_pwd = "L3e5F7u8";
    private final static String pkv = "PRI";
    private final static String dstr = "String";
    private final static String ddate = "Date";
    private final static String dint = "Integer";
    private final static String byt = "byte";
    private final static String dbg = "BigDecimal";
    private final static String denum = "enum";
    private static Map<String, List<Col>> colMap = new HashMap<String, List<Col>>();//key=table_name  val=col的list
    private static Map<String, String> tablMap = new HashMap<String, String>();
    private static Map<String, Col> keyMap = new HashMap<String, Col>(); //key=表名  val=col 只支持单主键

    //======实体类生成配置===============
    private final static String projectPath = System.getProperty("user.dir");

    private static String projectName = "water";
    //基础实体类的文件路径
    private static String POPath = projectPath + "/src/main/java/cn/lefull/" + projectName + "/entity/base";
    //基础实体类的包名
    private static String POPackage = "cn.lefull." + projectName + ".entity.base";

    //基础实体类的扩展文件路径
    private static String POPathExp = "";
    //基础实体类的扩展包名
    private static String POPackageExp = "";

    //dao层
    private static String DAOPath = "";
    private static String DAOPackage = "cn.lefull." + projectName + ".dao";
    //service层
    private static String ServicePath = "";
    private static String ServicePackage = "";
    //serviceimpl层
    private static String ServiceImplPath = "";
    private static String ServiceImplPackage = "";

    //mapper path
    private static String MapperPath = projectPath + "/src/main/resources/mapper/" + projectName + "";

    //mybatis-cofig.xml
    private static String Mybatis_config = projectPath + "/src/main/resources/mybatis-config.xml";
    public static void setProjectName(String projectName) {
        CreatCode.projectName = projectName;
        //repository 实体操作
//        CreatCode.POPath = projectPath + "/lefull-" + projectName + "-api-/src/main/java/cn/lefull/" + projectName + "/entity/base";
//        //基础实体类的包名
//        CreatCode.POPackage = "cn.lefull." + projectName + ".entity.base";

        //基础实体类的扩展文件路径
        CreatCode.POPathExp = projectPath + "/" + projectName + "/src/main/java/cn/lefull/jpa/entity";
        //基础实体类的扩展包名
        CreatCode.POPackageExp = "cn.lefull.jpa.entity";

        //repository层dao层
        CreatCode.DAOPath = projectPath + "/" + projectName + "/src/main/java/cn/lefull/jpa/repository";
        CreatCode.DAOPackage = "cn.lefull.jpa.repository";
        //service层
        CreatCode.ServicePath = projectPath + "/" + projectName + "/src/main/java/cn/lefull/jpa/service";
        CreatCode.ServicePackage = "cn.lefull.jpa.service";
        //serviceImpl层
        CreatCode.ServiceImplPath = projectPath + "/" + projectName + "/src/main/java/cn/lefull/jpa/service/impl";
        CreatCode.ServiceImplPackage = "cn.lefull.jpa.service.impl";

        //mapper path
//        CreatCode.MapperPath = projectPath + "/lefull_" + projectName + "/src/main/resources/mapper";
//
//        //mybatis-config.xml path
//        CreatCode.Mybatis_config = projectPath + "/lefull_" + projectName + "/src/main/resources/mybatis-config.xml";
    }

    public static void main(String[] args) throws Exception {
            System.out.println(projectPath);
        // System.out.println(creatBaseEntity("xb_course_order"));
        //   creatEntity("xb_course_order");
        //   test();
        //creatFile("D://tt.txt","\n\t6\n7");
        //creatDAO("xb_course_order");
        // System.out.println(creatMapper("xb_course_order"));
        //    XB_PAY_ORDER_RETURN
        //xb_pay_order  xb_pay_order_return  XB_SCTG_BUYinfo = infoDAO.getEntityByParamComm(info);
        //XB_WX_USER_RECEIVE
        //XB_ALL_SERVICE

        //创建mybatis
        // String tb = "intelligent_water_synchro_info";

        /// read(tb);
        // creatTblFile(tb.toLowerCase());

        //创建触发器
//        createTriggers("t2,t3,t4");
        // creatTblFile(tb.toLowerCase());
        //creatMoreTbl(tb);
        //  creatTblAlias("");
        // creatAll();


    }


    //获取表字段
    public static void read(String dataBase, String tb) throws Exception {
        tb = Tool.dropNull(tb);
        String sz[] = tb.split(",");
        String tbs = "";
        if (tb.length() != 0) {
            for (int i = 0; i < sz.length; i++) {
                String temp = sz[i].trim();
                if (temp.length() != 0) {
                    tbs = tbs + "," + "'" + temp + "'";
                }
            }
            if (tbs.startsWith(",")) {
                tbs = tbs.substring(1, tbs.length());
            }
        }


        Connection con = getCon();
        Statement st = con.createStatement();
        String insql = "";
        if (tbs.length() != 0) {
            insql = " AND TABLE_NAME in (" + tbs + ") ";
        }
        String sqlTable = "select  TABLE_NAME,table_comment FROM information_schema.tables   " +
                " where TABLE_SCHEMA='" + dataBase + "' " + insql + " ORDER BY TABLE_NAME";
        //System.out.println(sqlTable);
        ResultSet rsTable = st.executeQuery(sqlTable);
        while (rsTable.next()) {
            String tn = rsTable.getString("TABLE_NAME").toLowerCase().trim();
            String cmment = rsTable.getString("table_comment").trim();
            tablMap.put(tn, cmment);
        }

        String sql = "select  TABLE_NAME,COLUMN_NAME,data_type,COLUMN_key,COLUMN_COMMENT, ORDINAL_POSITION,COLUMN_TYPE  FROM information_schema.`COLUMNS`  " +
                " where TABLE_SCHEMA='" + dataBase + "' " + insql + " ORDER BY TABLE_NAME,ORDINAL_POSITION";
        System.out.println(sql);
        int tot = getTotColS(sql);
        ResultSet rs = st.executeQuery(sql);
        String tblName = "";
        List<Col> list = new Vector<Col>();
        int num = 0;
        while (rs.next()) {
            num++;
            String tn = rs.getString("TABLE_NAME").toLowerCase().trim();

            //tn= Tool.tuofengChange(tn,true);

            String cn = rs.getString("COLUMN_NAME").toLowerCase().trim();
            //cn=Tool.tuofengChange(cn,false);

            String ty = rs.getString("data_type").trim();
            String pk = rs.getString("COLUMN_key");
            String desc = rs.getString("COLUMN_COMMENT");
            String len = rs.getString("COLUMN_TYPE");
            if (desc == null) desc = "";
            Col col = null;
            if (ty.equals("int") || ty.equals("bigint") || ty.equals("long") || ty.equals("tinyint")) {
                ty = dint;
            } else if (ty.equals("date") || ty.equals("datetime")) {
                ty = ddate;
            } else if (ty.equals("float") || ty.equals("double") || ty.equals("decimal")) {
                ty = dbg;
            } else if (ty.equals("blob")) {
                ty = byt;
            } else if (ty.equals("enum")) {
                ty = denum;
                col = new Col(cn, desc, ty, colToEnums(len));
            } else {
                ty = dstr;
            }
            if (!ty.equals(denum)) {
                col = new Col(cn, desc, ty, colLength(len));
            }
            if (pkv.equals(pk)) {//主键
                keyMap.put(tn, col);
            }
            if (!tn.equals(tblName)) {//不相等
                if (tblName.length() != 0)
                    colMap.put(tblName, list);
                list = new Vector<Col>();
                tblName = tn;
            }
            list.add(col);
            if (tot == num)
                colMap.put(tn, list);

        }

        rs.close();
        st.close();
        con.close();

    }
    /**
     * 创建触发器
     *
     * @param tbls
     * @return
     */
    /*private final static String trigger_path = "/Users/macair/Documents";//生成文件路径

    public static String createTriggers(String tbls) throws Exception {
        StringBuffer sb = new StringBuffer("");
        tbls = Tool.dropNull(tbls);
        //读取字段
        read(tbls);
        String sz[] = tbls.split(",");
        String tbs = "";
        for (int i = 0; i < sz.length; i++) {
            String temp = sz[i].trim();
            if (temp.length() != 0) {
                sb.append(creaTrigger(temp));
            }
        }
        // System.out.println(sb.toString());

        createUtfFile(trigger_path + "/trigger" + DateUtil.getStrByDate(new Date(), DateUtil.date_gs) + ".sql", sb.toString());
        System.out.println("创建完成！");
        return sb.toString();
    }

    public static String creaTrigger(String tbl) {
        StringBuffer sb = new StringBuffer("");
        sb.append(getInsertTrigger(tbl));
        sb.append(getUpdateTrigger(tbl));
        return sb.toString();

    }

    *//**
     * 得到插入的触发器
     *
     * @param tbl
     * @return
     *//*
    public final static String trans_temp_cols = "trans_token,tbl_name,pk_col,pk_val,oper_type,change_type,cont_json,creat_time";

    private static String getInsertTrigger(String tbl) {
        StringBuffer sb = new StringBuffer("");
        String pk_col = keyMap.get(tbl).name;
        String trigger = tbl + "_after_insert";
        sb.append("\n");
        sb.append("delimiter ;\n");
        sb.append("DROP TRIGGER IF EXISTS `" + trigger + "`;\n");
        sb.append("delimiter ;;\n");
        sb.append("CREATE TRIGGER `" + trigger + "` AFTER INSERT ON `" + tbl + "` FOR EACH ROW BEGIN\n");
        sb.append("INSERT  into sys_trans_temp\n");
        sb.append("(" + trans_temp_cols + ")\n");
        sb.append("values\n");
        sb.append("(NEW.trans_token,'" + tbl + "','" + pk_col + "',NEW." + pk_col + ",'insert','after','',unix_timestamp(now()));\n");
        sb.append("END\n");
        sb.append(" ;;\n");

        return sb.toString();
    }

    *//**
     * 修改触发器
     *
     * @param tbl
     * @return
     *//*
    private static String getUpdateTrigger(String tbl) {
        StringBuffer sb = new StringBuffer("");
        String trigger = tbl + "_after_update";
        String pk_col = keyMap.get(tbl).name;
        sb.append("\n");
        sb.append("delimiter ;\n");
        sb.append("DROP TRIGGER IF EXISTS `" + trigger + "`;\n");
        sb.append("delimiter ;;\n");
        sb.append("CREATE TRIGGER `" + trigger + "` AFTER UPDATE ON `" + tbl + "` FOR EACH ROW BEGIN\n");
        sb.append("DECLARE cont_new VARCHAR(65535);\n");
        sb.append("DECLARE cont_old VARCHAR(65535);\n");
        sb.append("DECLARE new_is_delete int(10);\n");
        sb.append("DECLARE old_is_delete  int(10);\n");
        sb.append("DECLARE data_num int(10);\n");
        sb.append("set new_is_delete=NEW.is_delete;\n");
        sb.append("set old_is_delete=OLD.is_delete;\n");
        sb.append("IF(new_is_delete=1 and old_is_delete=0) THEN #删除操作\n\n");
        sb.append("INSERT  into sys_trans_temp\n");
        sb.append("(" + trans_temp_cols + ")\n");
        sb.append("VALUES\n");
        sb.append("(OLD.trans_token,'" + tbl + "','" + pk_col + "',NEW." + pk_col + ",'delete','after','',unix_timestamp(now()));\n");
        sb.append("ELSEIF (new_is_delete=0 AND old_is_delete=1) THEN\n\n");
        sb.append("set new_is_delete=NEW.is_delete;\n");
        sb.append("\nELSE\n");
        sb.append("#----START------\n");
        sb.append("SELECT COUNT(*) INTO data_num FROM sys_trans_temp where trans_token=OLD.trans_token and "
                + "tbl_name='" + tbl + "' AND pk_col='" + pk_col + "' and pk_val=NEW." + pk_col + " and oper_type='update';\n\n");
        sb.append("IF(data_num<2) THEN \n");
        sb.append(getContJson(tbl));
        sb.append("INSERT  into sys_trans_temp\n");
        sb.append("(trans_token,tbl_name,pk_col,pk_val,oper_type,change_type,cont_json,creat_time)\n");
        sb.append("VALUES\n");
        sb.append("(NEW.trans_token,'" + tbl + "','" + pk_col + "',OLD." + pk_col + ",'update','before',cont_old,unix_timestamp(now()));\n");
        sb.append("\n");
        sb.append("INSERT  into sys_trans_temp\n");
        sb.append("(trans_token,tbl_name,pk_col,pk_val,oper_type,change_type,cont_json,creat_time)\n");
        sb.append("VALUES\n");
        sb.append("(NEW.trans_token,'" + tbl + "','" + pk_col + "',NEW." + pk_col + ",'update','after',cont_new,unix_timestamp(now()));\n");
        sb.append("\n");
        sb.append("END IF;\n");

        sb.append("#----------END-----\n");
        sb.append("end if;\n");
        sb.append("END\n");
        sb.append(" ;;\n");


        return sb.toString();
    }*/

    /**
     * 得到json内容
     *
     * @param
     * @return
     */
   /* private static String getContJson(String tbl) {
        StringBuffer sb = new StringBuffer("");

        String s1 = "";
        String s2 = "";
        List<Col> list = colMap.get(tbl);
        for (Col c : list) {
            s1 += "'\"" + c.name + "\":','\"',IFNULL(NEW." + c.name + ",''),'\"',',',";
            s2 += "'\"" + c.name + "\":','\"',IFNULL(OLD." + c.name + ",''),'\"',',',";
        }
        s1 = s1.substring(0, s1.length() - 5);
        s2 = s2.substring(0, s2.length() - 5);
        s1 = "SET cont_new=CONCAT('{'," + s1 + ",'}');\n\n";
        s2 = "SET cont_old=CONCAT('{'," + s2 + ",'}');\n\n";

        sb.append(s1);
        sb.append(s2);
        return sb.toString();
    }*/

    private static String[] colToEnums(String colType) {
        if (colType == null || colType.length() == 0 || colType.indexOf("(") == -1) return null;
        String s = colType.substring(colType.indexOf("(") + 1);
        s = s.substring(0, s.indexOf(")"));
        String[] enums = null;
        if (s.indexOf(",") != -1) {
            enums = s.replace("\'", "").trim().split(",");
        }
        return enums;
    }

    /**
     * 创建所有文件
     */
    public static void creatAll() throws Exception {
        creatFolder();//创建文件
        Set<String> keySet = colMap.keySet();//获取map的key值的集合，set集合
        for (String obj : keySet) {//遍历key
            creatTblFile(obj);
        }
        creatTblAlias("");//展现别名
    }

    //<typeAlias type="mybatis.entity.Test" alias="Test"/>
    public static String creatTblAlias(String tb_name) {
        StringBuffer sb = new StringBuffer();
        if (tb_name == null || tb_name.trim().length() == 0) {
            Set<String> keySet = colMap.keySet();//获取map的key值的集合，set集合
            for (String obj : keySet) {//遍历key

                String ClsName = Upfirst(obj);
                sb.append("\t\ttypeAlias type=\"" + POPackageExp + "." + ClsName + "\" alias=\"" + ClsName + "\"\n");
            }

        } else {
            String ClsName = Upfirst(tb_name);
            sb.append("typeAlias type=\"" + POPackageExp + "." + ClsName + "\" alias=\"" + ClsName + "\"");
        }
        System.out.println(sb.toString());
        return sb.toString();
    }

    /**
     * 创建更多的表用,隔离
     *
     * @param tbls
     */
    public static void creatMoreTbl(String tbls) throws Exception {
        tbls = Tool.dropNull(tbls);
        String sz[] = tbls.split(",");
        for (int i = 0; i < sz.length; i++) {
            String temp = sz[i].trim();
            if (temp.length() != 0) {
                creatTblFile(temp);
            }
        }
    }

    /**
     * 创建一个表的po dao mapper文件
     *
     * @param
     */
    public static void creatTblFile(String tb_names) throws Exception {
        System.out.println(tb_names);
        String tb_arr[] = tb_names.split(",");
        for (String tb_name : tb_arr) {
            tb_name = tb_name.toLowerCase().trim();
            //  tb_name=Tool.tuofengChange(tb_name,true);
            File file = new File(POPath.trim() + "/Base" + Upfirst(tb_name) + ".java");
            if(file.exists()){
                System.out.println("表已创建，如需覆盖，请先删除");
                continue;
            }
            //创建基础实体
            //creatBaseEntity(tb_name);
            //创建实体继承基础实体
            creatEntity(tb_name);
            //创建DAO文件
            creatDAO(tb_name);
//            //创建Mapper文件
//            //creatMapper(tb_name);
//            //修改mybatis—config添加配置
//            //mybatisAppend(tb_name);
//            //创建Service
            creatService(tb_name);
//            //创建ServiceImpl
            creatServiceImpl(tb_name);
        }

        //System.out.println(tb_name+"==创建完毕==");

    }

    public static void mybatisAppend(String tb_name) {
        File file = new File(Mybatis_config);
        if (!file.exists()) {
            System.out.print(Mybatis_config + "    文件不存在");
        }
        Document document = null;
        SAXReader saxReader = new SAXReader();
        try {
            document = saxReader.read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();

        Iterator<?> iter = root.elementIterator("typeAliases");
        String tblAlias = creatTblAlias(tb_name);
        while (iter.hasNext()) {
            Element empEle = (Element) iter.next();
            empEle.addElement(tblAlias);
            empEle.addComment(tablMap.get(tb_name));
            // 遍历employee节点下所有子节点

            /*Iterator<?> eleIte = empEle.elementIterator();

            while (eleIte.hasNext()) {

                Element ele = (Element) eleIte.next();

                System.out.println("<" + ele.getName() + ">" + ele.attribute("alias").getValue()+"  ===     "+ele.attribute("type").getValue());

            }*/
        }
        XMLWriter output = null;
        try {
            output = new XMLWriter(new FileWriter(file));

            output.write(document);

            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // String tblAlias =creatTblAlias(tb_name);

    }

    public static Connection getCon() throws Exception {
        Class.forName(diver);
        Connection con = DriverManager.getConnection(url, db_user, db_pwd);
        return con;

    }

    public static int getTotColS(String sql) throws Exception {
        int ret = 0;
        Connection con = getCon();
        Statement st = con.createStatement();
        sql = "select count(*) from (" + sql + ") as tt ";
        ResultSet rs = st.executeQuery(sql);
        rs.next();
        ret = rs.getInt(1);
        return ret;
    }

    public static void test() {
        System.out.println("表有--" + colMap.size());
        System.out.println("主键--" + keyMap.size());
        Set<String> keySet = colMap.keySet();//获取map的key值的集合，set集合
        for (String obj : keySet) {//遍历key
            System.out.println("table:" + obj + ",=========:" + colMap.get(obj));//输出键与值
        }
    }


    /**
     * 创建基础eneity类
     *
     * @param tb_name
     * @return
     */
    public static String creatBaseEntity(String tb_name) throws Exception {
        StringBuffer sb = new StringBuffer();
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sm = new StringBuffer();//方法
        boolean isBigDecimal = false;
        boolean isDate = false;
        StringBuffer toStringSb = new StringBuffer();//toString()

        sb.append("package " + POPackageExp.trim() + ";\n");
       // sb.append("import " + POPackage.trim() + ".Base" + ClsName + ";\n\n");

        sb.append("/***\n*基础实体\n*/\n");
//        @Table(name = "user")
//                @Entity
//                @Data

        sb.append("@MappedSuperclass\n");
        sb.append("@Data\n");
        sb.append("public class Base" + Upfirst(tb_name) + " extends BasicVo  implements java.io.Serializable{\n");
        sb.append("\tprivate static final long serialVersionUID = 1L;\n");


        List<Col> list = colMap.get(tb_name);
        int i = 0;
        for (Col c : list) {
            if (c.type.equals(dbg)) isBigDecimal = true;
            if (c.type.equals(ddate)) isDate = true;
            if (c.type.equals(ddate)) {
                sb.append("\t@JsonSerialize(using = CustomDateSerializer.class)\n");
            }
            sb.append("\tprivate " + c.type + "  " + c.name + " ;\t\t/**" + c.desc + "**/\n\n");

            sm.append("\tpublic " + c.type + " get" + Upfirst(c.name) + "() {   \n");
            sm.append("\t\t return " + c.name + ";   \n");
            sm.append("\t }  \n\n");

            sm.append("\tpublic void set" + Upfirst(c.name) + "(" + c.type + " " + c.name + ") {   \n");
            sm.append("\t\t this." + c.name + " = " + c.name + ";   \n");
            sm.append("\t } \n\n");
        }


        sb.append(sm);


        toStringSb.append("\n\t@Override\n");
        toStringSb.append("\tpublic String toString() {\n");
        toStringSb.append("\t\treturn   org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(this);  \n");
        toStringSb.append("\t}\n");

        sb.append(toStringSb);
        sb.append("}");

        sb1.append("package " + POPackage.trim() + ";\n");
        sb1.append("import cn.lefull.comm.util.BasicVo; \n");
        if (isBigDecimal) sb1.append("import java.math.BigDecimal; \n");
        if (isDate) sb1.append("import java.util.Date; \n");
        sb1.append("import com.fasterxml.jackson.databind.annotation.JsonSerialize;\n");
        sb1.append("import cn.lefull.comm.convert.CustomDateSerializer;\n");
        sb1.append("\n\n");
        sb1.append(sb);

        // System.out.println(sb1.toString());
        //创建文件
        createUtfFile(POPath.trim() + "/Base" + Upfirst(tb_name) + ".java", sb1.toString());
        return sb1.toString();
    }

    /**
     * 创建实体类扩展
     *
     * @param tb_name
     * @return
     * @throws Exception
     */
    public static String creatEntity(String tb_name) throws Exception {
        StringBuffer sb = new StringBuffer();
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sm = new StringBuffer();//方法
        boolean isBigDecimal = false;
        boolean isDate = false;


        String ClsName = Upfirst(tb_name);
        sb.append("package " + POPackageExp.trim() + ";\n\n");
        sb.append("import cn.lefull.jpa.entity.BaseEntity;\n");
        sb.append("import java.math.BigDecimal;\n");
        sb.append("import java.util.Date;\n");
        sb.append("import lombok.Data;\n");
        sb.append("import javax.persistence.*;\n");
        sb.append("import javax.persistence.*;\n");
        sb.append("import java.io.Serializable;\n");
        sb.append("import io.swagger.annotations.ApiModelProperty;\n\n");
        //sb.append("/***\n*" + tablMap.get(tb_name) + "\n*/\n");
        sb.append("/**\n");
        sb.append("* @description: "+tablMap.get(tb_name)+"\n");
        sb.append("* @author: qijiang email:jiang1211@foxmail.com \n");
        sb.append("* @date: "+DateTimeUtil.intDateToStr(DateTimeUtil.getTensTimeStamp()) +" \n");
        sb.append("*/\n");
        sb.append("@Table(name = \""+tb_name+"\")\n");
        sb.append("@Entity\n");
        sb.append("@Data\n");
        sb.append("public class " + ClsName + " extends  BaseEntity implements Serializable  {\n\n");
        sb.append("\tprivate static final long serialVersionUID = 1L;\n");
        List<Col> list = colMap.get(tb_name);
        int i = 0;
        for (Col c : list) {
            if (c.type.equals(dbg)) isBigDecimal = true;
            if (c.type.equals(ddate)) isDate = true;
//            if (c.type.equals(ddate)) {
//                sb.append("\t@JsonSerialize(using = CustomDateSerializer.class)\n");
//            }
            if(!("id".equals(c.name) ||("delete_time".equals(c.name))||("delete_status".equals(c.name)) || ("create_time".equals(c.name)) || ("update_time".equals(c.name)))){
                sb.append("\t\n");
                sb.append("\t/**"+c.desc+"**/\n");
                sb.append("\t@Column(name = \""+c.name+"\")\n");
                sb.append("\t@ApiModelProperty(value = \""+c.desc+"\",notes =\""+c.desc+"\" )\n");
                sb.append("\tprivate " + c.type + "  " + toLowerCaseFirstOne(Upfirst(c.name)) + " ;\n");
            }

//            sm.append("\tpublic " + c.type + " get" + Upfirst(c.name) + "() {   \n");
//            sm.append("\t\t return " + c.name + ";   \n");
//            sm.append("\t }  \n\n");

//            sm.append("\tpublic void set" + Upfirst(c.name) + "(" + c.type + " " + c.name + ") {   \n");
//            sm.append("\t\t this." + c.name + " = " + c.name + ";   \n");
//            sm.append("\t } \n\n");
        }


        sb.append(sm);

//        if (isBigDecimal) sb1.append("import java.math.BigDecimal; \n");
//        if (isDate) sb1.append("import java.util.Date; \n");
//        sb1.append("import com.fasterxml.jackson.databind.annotation.JsonSerialize;\n");
//        sb1.append("import cn.lefull.comm.convert.CustomDateSerializer;\n");
//        sb1.append("\n\n");
//        sb1.append(sb);


        sb.append("}\n");
        //System.out.println(sb.toString());
        //创建文件
        createUtfFile(POPathExp.trim() + "/" + ClsName + ".java", sb.toString());
        //打印别名
        //String bm = "<typeAlias  alias=\"" + ClsName + "\" type=\"" + POPackageExp + "." + ClsName + "\"/> \n";
        return sb.toString();
    }


    /**
     * 创建dao
     *
     * @return
     */
    public static String creatDAO(String tb_name) throws Exception {
        StringBuffer sb = new StringBuffer();
        String ClsName = Upfirst(tb_name);
        Col pk = (Col) keyMap.get(tb_name);
//        if (pk == null) pk = new Col("无主键", "无主键", "无主键", 1000);   //String name, String desc, String type

        sb.append("package " + DAOPackage + ";\n");
        //sb.append("import java.util.*;\n");
        //sb.append("import cn.lefull.common.config.BaseRepository;\n");
        sb.append("import " + POPackageExp + "." + ClsName + ";\n");
        sb.append("import org.springframework.data.jpa.repository.JpaRepository;\n");
        sb.append("\n");
        sb.append("/**\n");
        sb.append("* @description: "+tablMap.get(tb_name)+"\n");
        sb.append("* @author: qijiang email:jiang1211@foxmail.com \n");
        sb.append("* @date: "+DateTimeUtil.intDateToStr(DateTimeUtil.getTensTimeStamp()) +" \n");
        sb.append("*/\n");
        //sb.append("@Mapper\n");
        sb.append("public interface " + ClsName + "Repository extends JpaRepository<"+ClsName+",Long>{\n");

//        sb.append("\t//插入一条记录\n");
//        sb.append("\tpublic void   addEntity(" + ClsName + " " + tb_name + ");\n\n");
//        sb.append("\t//插入多条记录,如果非自增长主键，要手动填充主键\n");
//        sb.append("\tpublic void  addBatch(List<" + ClsName + "> list);\n\n");
//
//        if (pk != null) {
//            sb.append("\t//通过主键得到一条数据\n");
//            sb.append("\tpublic " + ClsName + "  getEntityByPk(@Param(\"" + pk.name + "\") " + pk.type + " " + pk.name + ");  \n\n");
//
//            sb.append("\t//得到所有数据\n");
//            sb.append("\tpublic List<" + ClsName + ">  getListAll();\n\n");
//
//            sb.append("\t//查询list传入通过Map或者实体类参数查询，属性为null或空的不加入where\n");
//            sb.append("\tpublic List<" + ClsName + ">  getListByParamComm(Object params);\n\n");
//
//            sb.append("\t//传入通过Map或者实体类参数查询，属性为null或空的不加入where\n");
//            sb.append("\tpublic " + ClsName + "  getEntityByParamComm(Object params);  \n\n");
//
//            sb.append("\t//通过主键删除一条数据 \n");
//            sb.append("\tpublic void   delByPk(@Param(\"" + pk.name + "\")" + pk.type + "  " + pk.name + ");\n\n");
//
//            sb.append("\t//通过一个主键数组删除对应数据\n");
//            sb.append("\tpublic void   delByPks(Object[]  " + pk.name + ");\n\n");
//
//            sb.append("\t//通过Map或者实体类参数删除，只能一个条件\n");
//            sb.append("\tpublic void  delByParamComm(Object params);\n\n");
//
//
//            sb.append("\t//通过配置修改字段来确定修改\n");
//            sb.append("\tpublic void UpdateDynamicField(" + ClsName + " " + tb_name + ");\n\n");
//
//            sb.append("\t//参数对象所有为null的属性都要把对应字段修改成null，适合整个表对应功能的修改\n");
//            sb.append("\tpublic void updateEntity(" + ClsName + " " + tb_name + ");  \n\n");
//
//            sb.append("\t//参数对象所有为null的属性的对应字段不修改，适合修改少数几个字段，注意设置null无效，谨慎使用\n");
//            sb.append("\tpublic void updateNoNullEntity(" + ClsName + " " + tb_name + ");\n");
//        }


        sb.append("}");
        // System.out.println(sb.toString());
        //创建文件
        createUtfFile(DAOPath.trim() + "/" + ClsName + "Repository.java", sb.toString());
        return sb.toString();

    }
    /**
     * 创建service
     *
     * @return
     */
    public static String creatService(String tb_name) throws Exception {
        StringBuffer sb = new StringBuffer();
        String ClsName = Upfirst(tb_name);
        Col pk = (Col) keyMap.get(tb_name);
//        if (pk == null) pk = new Col("无主键", "无主键", "无主键", 1000);   //String name, String desc, String type

        sb.append("package " + ServicePackage + ";\n");
        sb.append("\n");
        sb.append("/**\n");
        sb.append("* @description: "+tablMap.get(tb_name)+"\n");
        sb.append("* @author: qijiang email:jiang1211@foxmail.com \n");
        sb.append("* @date: "+DateTimeUtil.intDateToStr(DateTimeUtil.getTensTimeStamp()) +" \n");
        sb.append("*/\n");
        sb.append("public interface " + ClsName + "Service {\n");
        sb.append("}");
        // System.out.println(sb.toString());
        //创建文件
        createUtfFile(ServicePath.trim() + "/" + ClsName + "Service.java", sb.toString());
        return sb.toString();

    }
    /**
     * 创建serviceimpl
     *
     * @return
     */
    public static String creatServiceImpl(String tb_name) throws Exception {
        StringBuffer sb = new StringBuffer();
        String ClsName = Upfirst(tb_name);
        String clsName = toLowerCaseFirstOne(ClsName);
        Col pk = (Col) keyMap.get(tb_name);
//        if (pk == null) pk = new Col("无主键", "无主键", "无主键", 1000);   //String name, String desc, String type

        sb.append("package " + ServiceImplPackage + ";\n");
        sb.append("\n");
        sb.append("import "+ServicePackage+"."+ClsName+"Service;\n");
        sb.append("import "+"lombok.extern.slf4j.Slf4j;\n");
        sb.append("import "+"org.springframework.stereotype.Service;\n\n");
        sb.append("/**\n");
        sb.append("* @description: "+tablMap.get(tb_name)+"\n");
        sb.append("* @author: qijiang email:jiang1211@foxmail.com \n");
        sb.append("* @date: "+DateTimeUtil.intDateToStr(DateTimeUtil.getTensTimeStamp()) +" \n");
        sb.append("*/\n");
        sb.append("@Service(\""+clsName+"Service\")\n")  ;
        sb.append("@Slf4j\n")  ;
        sb.append("public class " + ClsName + "ServiceImpl implements "+ClsName+"Service {\n");
        sb.append("}");
        // System.out.println(sb.toString());
        //创建文件
        createUtfFile(ServiceImplPath.trim() + "/" + ClsName + "ServiceImpl.java", sb.toString());
        return sb.toString();

    }
    /**
     * 创建Mapper文件
     *
     * @param tb_name
     * @return
     */
    public static String creatMapper(String tb_name) throws Exception {
        boolean isLogicDel = isLogicDel(tb_name);

        StringBuffer sb = new StringBuffer();
        String ClsName = Upfirst(tb_name);
        Col pk = (Col) keyMap.get(tb_name);
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>  \n");
        sb.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">  \n");
        sb.append("\t<mapper namespace=\"" + DAOPackage + "." + ClsName + "Dao" + "\"> \n\n");

        sb.append("\t<!-- 插入一条记录 -->\n");
        sb.append("\t<insert id=\"addEntity\" parameterType=\"" + ClsName + "\"  >\n");

        sb.append("\t\tinsert into " + tb_name + "\n");
        sb.append("\t"+createInsertSQL(tb_name, false));
        sb.append("\t</insert>\n\n");

        sb.append("\t<!-- 批量插入，注意，如果是非自增长主键，要把主键先生成 uuid -->\n");
        sb.append("\t<insert id=\"addBatch\" parameterType=\"java.util.List\" >\n");
        sb.append("\t\tinsert into " + tb_name + "\n");
        sb.append("\t"+createInsertSQL(tb_name, true));
        sb.append("\t</insert>\n\n");


        if (pk != null) {
            sb.append("\t<!-- 参数对象所有为null的属性都要把对应字段修改成null,适用于整张表修改的功能,谨慎使用 -->\n");
            sb.append("\t<update id=\"updateEntity\" parameterType=\"" + ClsName + "\" >\n");
            sb.append("\t\tupdate  " + tb_name + "  set  \n");
            sb.append("\t"+updateSQL(tb_name));
            sb.append("\t</update> \n\n");

            sb.append("\t<!-- 通过配置强制修改字段来修改 --> \n");
            sb.append("\t<update id=\"updateDynamicField\" parameterType=\"" + ClsName + "\" > \n");
            sb.append("\t\tupdate  " + tb_name + "  \n");
            sb.append("\t"+updateDynamicField(tb_name));
            sb.append("\t</update>\n\n");

            sb.append("\t<!-- 参数对象所有为null的属性的对应字段不修改，适合修改少数几个字段，注意设置null无效，谨慎使用 --> \n");
            sb.append("\t<update id=\"updateNoNullEntity\" parameterType=\"" + ClsName + "\" > \n");
            sb.append("\t\tupdate  " + tb_name + "  \n");
            sb.append("\t"+updateSQLBath(tb_name));
            sb.append("\t</update>\n\n");


            sb.append("\t<!-- 通过主键查询 -->\n");
            sb.append("\t<select id=\"getEntityByPk\" parameterType=\"" + getType(pk.type) + "\"  resultType=\"" + ClsName + "\"> \n");
            sb.append("\t\tselect * from " + tb_name + "  where  " + pk.name + "=#{" + pk.name + "} \n");
            sb.append("\t</select>\n\n");

            sb.append("\t<!-- 通过主键删除一条数据 --> \n");
            sb.append("\t<update id=\"delByPk\" parameterType=\"" + getType(pk.type) + "\"> \n");
            if (isLogicDel) {
                sb.append("\t\tupdate " + tb_name + " set " + is_delete + "=1," + delete_time + "=  unix_timestamp(now()) " + " where " + pk.name + " =#{" + pk.name + "} \n");
            } else {
                sb.append("\t\tdelete from " + tb_name + " where " + pk.name + " =#{" + pk.name + "} \n");
            }

            sb.append("\t</update>\n\n");

            sb.append("\t<!--  通过一个主键数组删除对应数据-->\n");
            sb.append("\t<update id=\"delByPks\" >\n");
            if (isLogicDel) {//逻辑删除
                sb.append("\t\tupdate " + tb_name + " set " + is_delete + "=1," + delete_time + "=unix_timestamp(now())   where " + pk.name + "  in\n");
                sb.append("\t\t<foreach collection=\"array\" index=\"index\"   item=\"item\" open=\"(\" separator=\",\" close=\")\"> \n");
                sb.append("\t\t\t#{item}   \n");
                sb.append("\t\t</foreach> \n");
            } else {
                sb.append("\t\tdelete from " + tb_name + "  where " + pk.name + "  in\n");
                sb.append("\t\t<foreach collection=\"array\" index=\"index\"   item=\"item\" open=\"(\" separator=\",\" close=\")\"> \n");
                sb.append("\t\t\t\t#{item}   \n");
                sb.append("\t\t</foreach> \n");
            }

            sb.append("\t</update>\n\n");


            sb.append("\t<!-- 查询所有 -->\n");
            sb.append("\t<select id=\"getListAll\" resultType=\"" + ClsName + "\" >\n");
            String delSQL = "";
            if (isLogicDel) {//是逻辑删除
                delSQL = " where " + is_delete + "=0";
            }
            sb.append("\t\tselect * from " + tb_name + delSQL + " \n");
            sb.append("\t</select>\n\n");

            sb.append("\t<!-- 传入对象为查询参数，属性为null或空的不加入where -->\n");
            sb.append("\t<select id=\"getListByParamComm\" resultType=\"" + ClsName + "\" >\n");
            sb.append("\t\tselect * from " + tb_name + "\n");
            sb.append("\t\twhere ");
            if (isLogicDel) {//逻辑删除
                sb.append(" " + is_delete + "=0 \n");
            } else {
                sb.append(" 1=1 \n");
            }

            sb.append(whereSql(tb_name));

            sb.append("\t</select>\n\n");

            sb.append("\t<!-- 传入对象为查询参数，属性为null或空的不加入where -->\n");
            sb.append("\t<select id=\"getEntityByParamComm\" resultType=\"" + ClsName + "\" >\n");
            sb.append("\t\tselect * from " + tb_name + "  \n");
            sb.append("\t\twhere ");
            if (isLogicDel) {//逻辑删除
                sb.append(" " + is_delete + "=0 \n");
            } else {
                sb.append(" 1=1 \n");
            }

            sb.append(whereSql(tb_name));

            sb.append("\t\tlimit 1 \n \t</select>\n\n");

            sb.append("\t<!-- 通过Map或者实体类参数删除，只能一个条件,严禁用or链接 -->\n");
            sb.append("\t<update id=\"delByParamComm\" >\n");
            if (isLogicDel) {//逻辑删除
                sb.append("\t\tupdate " + tb_name + " set " + is_delete + "=1," + delete_time + "=unix_timestamp(now()) \n");
            } else {
                sb.append("\t\tdelete from " + tb_name + " \n");
            }

            sb.append("\t\twhere 1=1 \n");
            sb.append("\t"+creatDelSql(tb_name));
            sb.append("\t</update>\n\n");
        }


        sb.append("<!--**********单表操作完毕************************-->");
        sb.append(" \n\n");

        sb.append("</mapper>  \n");
        //System.out.println(sb.toString());
        //创建文件

        createUtfFile(MapperPath + "/" + ClsName + "Mapper.xml", sb.toString());
        return sb.toString();
    }

    /**
     * 创建utf文件
     *
     * @param filePath
     * @param content
     * @throws Exception
     */
    public static void createUtfFile(String filePath, String content) throws Exception {
        String path = filePath.substring(0, filePath.lastIndexOf("/"));

        File file = new File(path);
        if (!file.isDirectory()) {
            file.mkdirs();
        }
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(filePath), "utf-8");
        out.write(content);
        //out.flush();
        out.close();

    }


    private static String createInsertSQL(String tblName, boolean isBatch) {
        String ret = "";
        String s1 = "";
        String s2 = "";
        List<Col> list = colMap.get(tblName);
        Col pk = (Col) keyMap.get(tblName);
        for (int i = 0; i < list.size(); i++) {
            Col c = list.get(i);
            if (pk.name.equals(c.name)) {
                s1 += "\t" + c.name + ",\n";
            } else {
                if (!is_delete.equals(c.name.trim()) && !create_time.equals(c.name.trim()) && !update_time.equals(c.name.trim()) && !delete_time.equals(c.name.trim())){
                    s1 += "\t\t\t<if test=\"" + c.name + "!=null\">" + c.name + ",</if> \n";
                }
            }
            if (!is_delete.equals(c.name.trim()) && !create_time.equals(c.name.trim()) && !update_time.equals(c.name.trim()) && !delete_time.equals(c.name.trim())) {
                if (isBatch) {
                    if (pk.name.equals(c.name)) {
                        s2 += "\t\t\t#{o." + c.name.trim() + "},\n";
                    } else {
                        s2 += "\t\t\t<if test=\"o." + c.name + "!=null\">" + "#{o." + c.name.trim() + "},</if>\n";
                    }
                } else {
                    if (pk.name.equals(c.name)) {
                        s2 += "\t\t\t#{" + c.name.trim() + "},\n";
                    } else {
                        s2 += "\t\t\t<if test=\"" + c.name + "!=null\">" + "#{" + c.name.trim() + "},</if>\n";
                    }
                }
            }
        }
        s1 += "\t\t\tcreate_time,\n\t\t\tis_delete,\n\t\t\tupdate_time,\n\t\t\tdelete_time\n";
        s2 += "\t\t\tunix_timestamp(now()),\n\t\t\t0,\n\t\t\t0,\n\t\t\t0\n";
        if (isBatch) {
            ret = "\t(" + s1 + "\t\t)\n";
            ret += "\t\tvalues\n";
            ret += "\t\t<foreach collection=\"list\" item=\"o\"  index=\"index\" separator=\",\" >\n";
            ret += "\t\t" +
                    "(\n" + s2 + "\t\t)\n";
            ret += "\t\t</foreach>\n";
            return ret;
        }
        ret = "\t(" + s1 + "\t\t)\n"
                + "\t\tvalues\n"
                + "\t\t(\n" + s2 + "\t\t)\n";
        return ret;
    }

    /**
     * @param tblName
     * @return
     */
    private static String updateSQL(String tblName) {
        StringBuffer sb = new StringBuffer();
        String str = "";
        List<Col> list = colMap.get(tblName);
        Col pk = (Col) keyMap.get(tblName);
        sb.append("\t\t");
//        if (pk == null) pk = new Col("无主键", "无主键", "无主键", 1000);   //String name, String desc, String type
        for (Col c : list) {
            //创建日期\删除标志\删除日期字段排除
            if (create_time.equals(c.name) || is_delete.equals(c.name) || delete_time.equals(c.name)) {
                continue;
            }

            if (c.name.equals(pk.name))
                continue;
            if (update_time.equals(c.name.trim())) {//修改日期
                str += c.name + "= unix_timestamp(now()),";
            } else
                str += c.name + "= #{" + c.name + "},";
        }
        str = str.substring(0, str.length() - 1);
        sb.append(str + "\n");
        sb.append("\t\twhere " + pk.name + "=#{" + pk.name + "}\n ");

        return sb.toString();
    }

    private static String updateSQLBath(String tblName) {
        StringBuffer sb = new StringBuffer();
        List<Col> list = colMap.get(tblName);
        Col pk = (Col) keyMap.get(tblName);
        sb.append("\t<trim prefix=\"set\"   suffixOverrides=\" ,\">  \n");

//        if (pk == null) pk = new Col("无主键", "无主键", "无主键", 1000);   //String name, String desc, String type
        for (Col c : list) {
            if (create_time.equals(c.name) || is_delete.equals(c.name) || delete_time.equals(c.name)) {
                continue;
            }
            if (c.name.equals(pk.name))
                continue;
            if (update_time.equals(c.name)) {
                sb.append("\t\t\t<if test=\"1==1\">" + c.name + "=unix_timestamp(now()),</if> \n");
            } else {
                sb.append("\t\t\t<if test=\"" + c.name + "!=null\">" + c.name + "=#{" + c.name + "},</if> \n");
            }

        }
        sb.append("\t\t</trim>\n");
        sb.append("\t\twhere " + pk.name + " =#{" + pk.name + "}\n ");

        return sb.toString();
    }

    private static String updateDynamicField(String tblName) {
        StringBuffer sb = new StringBuffer();
        List<Col> list = colMap.get(tblName);
        Col pk = (Col) keyMap.get(tblName);
        sb.append("\t<trim prefix=\"set\"   suffixOverrides=\" ,\">  \n");

//        if (pk == null) pk = new Col("无主键", "无主键", "无主键", 1000);   //String name, String desc, String type
        for (Col c : list) {
            if (create_time.equals(c.name) || is_delete.equals(c.name) || delete_time.equals(c.name)) {
                continue;
            }
            if (c.name.equals(pk.name))
                continue;
            if (update_time.equals(c.name)) {
                sb.append("\t\t\t<if test=\"1==1\">" + c.name + "=unix_timestamp(now()),</if> \n");
            } else {
                sb.append("\t\t\t<if test=\"updateFields." + c.name + "!=null\">" + c.name + "=#{" + c.name + "},</if> \n");
            }

        }
        sb.append("\t\t</trim>\n");
        sb.append("\t\twhere " + pk.name + " =#{" + pk.name + "}\n ");

        return sb.toString();
    }


    private static String whereSql(String tblName) {
        StringBuffer sb = new StringBuffer();
        List<Col> list = colMap.get(tblName);
        Col pk = (Col) keyMap.get(tblName);
//        if (pk == null) pk = new Col("无主键", "无主键", "无主键", 1000);   //String name, String desc, String type
        int i = 0;
        String type = "";

        for (Col c : list) {
            if (is_delete.equals(c.name) || create_time.equals(c.name) || delete_time.equals(c.name) || update_time.equals(c.name))
                continue;
            type = c.type;
            String strPre = "";//字符型前缀

            if (pk != null && "string".equals(pk.type.toLowerCase())) {
                strPre = "  and " + c.name + "!=''";
            }

            sb.append("\t\t<if test=\"" + c.name + "!=null  " + strPre + " \"> and " + c.name + "=#{" + c.name + "}</if><!--  " + c.desc + "  -->\n");

            i++;

        }

        return sb.toString();
    }

    public static String creatDelSql(String tblName) {
        StringBuffer sb = new StringBuffer();
        List<Col> list = colMap.get(tblName);
        Col pk = (Col) keyMap.get(tblName);
//        if (pk == null) pk = new Col("无主键", "无主键", "无主键", 1000);   //String name, String desc, String type
        String empty = "";
        for (Col c : list) {
            if (c.name.equals(pk.name) || c.len == 50 || c.name.equals("org_sn") || c.name.equals("org_id")) {//只显示主键\外键\机构id
                if (c.type.equals(dstr)) empty = "  and  " + c.name + " !=''";
                sb.append("\t<if test=\"" + c.name + "  != null  " + empty + "\"> and " + c.name + "=#{" + c.name + "}</if><!-- " + c.desc + " -->\n");
            }

        }
        return sb.toString();

    }

    private static String getType(String type) {
        String ret = "string";
        if (dint.equals(type))
            ret = "int";
        return ret;
    }

    //	/varchar(255)
    private static int colLength(String colType) {
        int ret = 1000;
        //  System.out.println(colType + "======");
        if (colType == null || colType.length() == 0 || colType.indexOf("(") == -1)
            return ret;
        String s = colType.substring(colType.indexOf("(") + 1);
        s = s.substring(0, s.indexOf(")"));
        if (s.indexOf(",") != -1) {
            s = s.substring(0, s.indexOf(","));
        }
        return Integer.parseInt(s);
    }

    /**
     * @return java.lang.String
     * @author Lcc
     * @Desc 首字母转驼峰，下划线转驼峰
     * @version 2018/7/17 下午12:14
     * @Param [str]
     **/
    public static String Upfirst(String str) {
        str = str.substring(0, 1).toUpperCase() + str.substring(1);
        str = StringTool.camel(new StringBuffer(str)).toString();
        return str;
    }
    /**
     *
     * @author qijiang @Email jiang1211@foxmail.com
     * @date 2018/10/23 上午10:22
     * @Param [s]
     * @return java.lang.String
     * @Description 首字母转小写
     */
    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }
    /**
     * 判断文件如果不存在则创建文件夹
     */
    public static void creatFolder() throws Exception {
        String po = POPath;
        String basepo = POPath + "/base";
        String dao = DAOPath;
        String mapper = DAOPath + "/mapper";

        folder(po);
        folder(basepo);
        folder(dao);
        folder(mapper);
    }

    private static void folder(String path) throws Exception {
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
    }
    /**
     * 是否存在逻辑删除
     *
     * @param tblName
     * @return
     */
    private static boolean isLogicDel(String tblName) {
        boolean ret = false;
        List<Col> list = colMap.get(tblName);
        for (Col c : list) {
            if (c.name.equals(is_delete)) {
                ret = true;
            }
        }


        return ret;
    }

}
